//
//  UserAccountViewModel.swift
//  Stauts
//
//  Created by Kylin on 16/3/17.
//  Copyright © 2016年 Kylin. All rights reserved.
//

import UIKit
typealias SuccessCallBack = (isSuccess : Bool) -> ()
class UserAccountViewModel{

    /// 将视图模型设计成单例模式
    static let shareManager : UserAccountViewModel = UserAccountViewModel()
    
    /// 用户帐号属性
    var account : UserAccount?
    
    /// 用户判断是否登陆成功的属性
    var isLogin : Bool {
        return account != nil && !isExpire
    }
    
    /// 判断AccessToken是否过期
    var isExpire : Bool {
        guard let expire_date = account?.expires_date else {
            return true
        }
        
        // 如果有效时间比当前时间要大,那么说明授权有效 返回true
      return expire_date.compare(NSDate()) == NSComparisonResult.OrderedAscending
        
    }
    
     /// 沙盒路径的计算属性
    var accountPath : String {
        
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
        // 拼接路径
        return(path as NSString).stringByAppendingPathComponent("accout.plist")
    }
    
    // MARK:- 构造函数
    init() {
        
        // 解档读取文件
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
    }
}



// MARK:- 对控制器的代码进行封装
extension UserAccountViewModel {
    func loadAccessToken(codeString : String,isSuccess : SuccessCallBack ) {
        
        NetworTools.shareManager.loadAccessToken(codeString) { (result, error) -> () in
            // 检测错误
            if error != nil{
                print(error)
                isSuccess(isSuccess: false)
                return
            }
            
            // 2.获取字典的结果
            guard let userInfoDict = result else {
                isSuccess(isSuccess: false)
                return
            }
            // 3.字典转成模型对象
            let account = UserAccount(dict: userInfoDict)
            
            // 请求用户数据
            self.loadUserInfo(account,isSuccess: isSuccess)
            
            
        }
    }
    
    func loadUserInfo(account : UserAccount,isSuccess : SuccessCallBack) {
        // 1.获取AccessToken和uid
        guard let accessToken = account.access_token ,uid = account.uid else {
            isSuccess(isSuccess: false)
            return
        }
        
        // 2:请求用户数据
        NetworTools.shareManager.loadUserInfo(accessToken, uid: uid) { (result, error) -> () in
            
            if error != nil {
                print(error)
                 isSuccess(isSuccess: false)
                return
            }
            // 3:获取字典结果
            guard let userInfoDict = result else {
                 isSuccess(isSuccess: false)
                return
            }
            
            // 4:从字典中取出头像各昵称
            account.avatar_large = userInfoDict["avatar_large"] as? String
            account.screen_name = userInfoDict["screen_name"] as? String
            
            // 5:保存帐号信息
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
            
            // 6:将创建出来的用户对象赋值给account属性
//            print(self.accountPath)
            self.account = account
            
            // 回调成功加载数据
           isSuccess(isSuccess: true)
        }
    }
}